package com.yupi.springbootinit.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yupi.springbootinit.bizmq.BiMessageProducer;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.RedisLimiterManager;
import com.yupi.springbootinit.model.dto.chart.GenChartByAiRequest;
import com.yupi.springbootinit.model.dto.reverse.ServerLoadInfo;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.ScoreChangeEnum;
import com.yupi.springbootinit.model.vo.BiResponse;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserScoreService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.utils.ServerMetricsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/wenxin")
@Slf4j
public class WenxinController {


        @Resource
        private UserService userService;
        @Resource
        private RedisLimiterManager redisLimiterManager;
        @Resource
        private ChartService chartService;
        @Resource
        private BiMessageProducer biMessageProducer;

        /**
         * 智能图表(异步) : 消息队列
         * 文心一言
         *
         */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByWenxin(@RequestPart("file") MultipartFile multipartFile,
                                                        GenChartByAiRequest chartRequest, HttpServletRequest request) {
        // 1.save chat(Not Generated)
        // 取出数据
        String name = chartRequest.getName();
        String goal = chartRequest.getGoal();
        String chartType = chartRequest.getChartType();
        // 校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空!");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长!");
        // 获取用户信息
        User user = userService.getLoginUser(request);
        Long userId = user.getId();
        // redisLimiterManager.doRateLimit(RedisConstant.GEN_CHART_LIMIT_KEY + user.getId());
        redisLimiterManager.doRateLimit(String.valueOf(userId));
        // 校验文件
        ExcelUtils.checkExcelFile(multipartFile);
        // 读取文件信息
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        ThrowUtils.throwIf(csvData.length() > 1000, ErrorCode.SYSTEM_ERROR, "原始信息过长!");
        // 插入数据到数据库
        Chart chartEntity = new Chart();
        chartEntity.setUserId(userId);
        chartEntity.setName(name);
        chartEntity.setGoal(goal);
        chartEntity.setGenType(UserConstant.WENXIN_TYPE);
        chartEntity.setStatus(FileConstant.WAIT);
        chartEntity.setChartType(chartType);
        boolean save = chartService.save(chartEntity);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "保存图表失败!");
        chartEntity.setChartData(csvData);
        // 将用户上传文件数据分表创建并存入一个新表
        Long entityId = chartEntity.getId();
        chartService.setChartData(csvData, entityId);

        // 将消息放入消息队列中
        biMessageProducer.sendMessageByWenxin(String.valueOf(entityId));

        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(entityId);
        return ResultUtils.success(biResponse);
    }

    /**
    public static void main(String[] args) {
        String response = "{\"id\":\"as-agirnym2vb\",\"object\":\"chat.completion\",\"created\":1704968093,\"result\":\"你好！我是零一万物开发的一个智能助手。\",\"is_truncated\":false,\"need_clear_history\":false,\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":41,\"total_tokens\":44}}";

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response);

            if (jsonNode.hasNonNull("result")){
                String result = jsonNode.get("result").asText();
                System.out.println(result);
            }
            if (jsonNode.hasNonNull("error_code")){
                int token = jsonNode.get("error_code").asInt();
                if (token == 110){

                }
            }
            // System.out.println(token);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

public static void main(String[] args) throws IOException {
    String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=ow3heQ59CQPKfECqyz3MnUFE&client_secret=kyIYETAmCMH3uPS9bfI5Lm1PAPVGru2g";
    // client_id=ow3heQ59CQPKfECqyz3MnUFE
    // client_secret=kyIYETAmCMH3uPS9bfI5Lm1PAPVGru2g

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(url);

    // 设置请求头
    httpPost.setHeader("Content-type", "application/json");
    httpPost.addHeader("Accept", "application/json");

    // 执行请求并获取响应
    HttpResponse response = httpClient.execute(httpPost);
    String result = EntityUtils.toString(response.getEntity());
    System.out.println("返回3"+result);
}

     */
}
